package com.blog.controller.admin;

import com.blog.constant.ErrorConstant;
import com.blog.constant.LogActions;
import com.blog.constant.WebConst;
import com.blog.controller.BaseController;
import com.blog.dto.StatisticsDto;
import com.blog.exception.BusinessException;
import com.blog.model.Comment;
import com.blog.model.Content;
import com.blog.model.Logger;
import com.blog.model.User;
import com.blog.service.log.LogService;
import com.blog.service.site.SiteService;
import com.blog.service.user.UserService;
import com.blog.utils.GsonUtils;
import com.blog.utils.ResultVoUtil;
import com.blog.utils.TaleUtils;
import com.blog.vo.ResultVo;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.List;

/**
 * index首页
 *
 * @author wmb
 *
 * @since 2021-2-8
 */
@Api("后台相关接口")
@Controller
public class IndexController extends BaseController {

    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    @Qualifier("siteService")
    private SiteService siteService;

    @Autowired
    @Qualifier("logService")
    private LogService logService;

    @Autowired
    @Qualifier("userService")
    private UserService userService;

    @ApiOperation("进入首页")
    @GetMapping({"/admin", "/admin/index"})
    public String index(HttpServletRequest request) {
        LOGGER.info("Enter admin index method");

        // 获取评论数
        List<Comment> commentList = siteService.getComments(5);
        // 获取最新文章数
        List<Content> contentList = siteService.getNewArticles(5);
        // 总计数
        StatisticsDto statistics = siteService.getStatistics();
        // 取最新的5条日志
        PageInfo<Logger> loggerPageInfo = logService.getLoggers(1, 5);
        List<Logger> loggerList = loggerPageInfo.getList();

        request.setAttribute("comments", commentList);
        request.setAttribute("articles", contentList);
        request.setAttribute("statistics", statistics);
        request.setAttribute("logs", loggerList);

        LOGGER.info("Exit admin index method");
        return "admin/index";
    }

    @ApiOperation("个人设置页面")
    @GetMapping("/admin/profile")
    public String profile() {
        return "admin/profile";
    }

    @ApiOperation("保存个人信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "nickname", value = "昵称，昵称不允许为空", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "email", value = "邮箱，邮箱不允许为空", paramType = "query", dataType = "String", required = true)
    })
    @PostMapping("/admin/profile")
    @ResponseBody
    public ResultVo saveProfile(@NotBlank(message = "昵称不允许为空") @RequestParam(value = "nickname") String nickname,
                                @NotBlank(message = "邮箱不允许为空") @RequestParam(value = "email") String email,
                                @ApiIgnore HttpServletRequest request,
                                @ApiIgnore HttpSession session) {
        User sessionUser = super.user(request);

        // 更新user表数据
        User user = new User();
        user.setUid(sessionUser.getUid());
        user.setNickname(nickname);
        user.setEmail(email);
        userService.updateUserInfo(user);
        logService.addLog(LogActions.UPDATE_USER_INFO.getAction(), GsonUtils.toJsonString(user), request.getRemoteAddr(), super.getUid(request));

        // 更新session中的数据
        sessionUser.setNickname(nickname);
        sessionUser.setEmail(email);
        session.setAttribute(WebConst.LOGIN_SESSION_KEY, sessionUser);

        return ResultVoUtil.success();
    }

    @ApiOperation("修改用户密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPassword", value = "旧密码，旧密码不允许为空", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "newPassword", value = "新密码，新密码不允许为空", paramType = "query", dataType = "String", required = true)
    })
    @PostMapping("/admin/password")
    @ResponseBody
    public ResultVo updatePassword(@NotBlank(message = "旧密码不允许为空") @RequestParam("oldPassword") String oldPassword,
                                   @Size(min = 6, max = 14, message = "请输入6-14位密码") @NotBlank(message = "新密码不允许为空") @RequestParam("newPassword") String newPassword,
                                   @ApiIgnore HttpServletRequest request,
                                   @ApiIgnore HttpSession session) {

        User sessionUser = super.user(request);
        if (!sessionUser.getPassword().equals(TaleUtils.MD5encode(sessionUser.getUsername() + oldPassword))) {
            return ResultVoUtil.error(ErrorConstant.OLD_PASSWORD_IS_ERROR);
        }

        try {
            // 更新用户密码
            User user = new User();
            user.setUid(sessionUser.getUid());
            String password = TaleUtils.MD5encode(sessionUser.getUsername() + newPassword);
            user.setPassword(password);
            userService.updateUserInfo(user);
            logService.addLog(LogActions.UPDATE_PASSWORD.getAction(), null, request.getRemoteAddr(), super.getUid(request));

            return ResultVoUtil.success();
        } catch (Exception e) {
            String message = "密码修改失败";
            if (e instanceof BusinessException) {
                message = e.getMessage();
            } else {
                LOGGER.error(message, e);
            }
            return ResultVoUtil.error(message);
        }
    }

}
